package cn.xy.org.service.impl;

import cn.xy.basic.service.impl.BaseServiceImpl;
import cn.xy.basic.util.PageList;
import cn.xy.org.domain.Department;
import cn.xy.org.mapper.DepartmentMapper;
import cn.xy.org.query.DepartmentQuery;
import cn.xy.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务层实现类
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> queryTree() {
        //先查询出所有数据
        List<Department> departments = departmentMapper.loadAll();
        //新建hashmap
        Map<Long, Department> allDepts = new HashMap<>();
        //将查询出的所有数据遍历出来，以键值对应的方式放入HashMap中,数据id对应数据。
        for (Department department : departments) {
            allDepts.put(department.getId(), department);

        }
        //找到第一层级，需要先新建集合对象，再将第一层级数据添加进集合
        List<Department> firstDepts = new ArrayList<>();
        for (Department tmp : departments) {
            //所有数据遍历出来，判断parent_id是否为null,为null则为第一层级
            if(tmp.getParent_id()==null){
                //得到第一层级，添加进第一层级集合，
                firstDepts.add(tmp);

            }else {
                //不属于第一层级的，则找自己的上级，并且将自己放入上级的children中。
                Department parent = allDepts.get(tmp.getParent_id());
                if(parent!=null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDepts;
    }








}
